from django.views.generic import View
from django.db.models import F, Q
from django.utils import timezone
from libs.parser import JsonParser, Argument
from libs.utils import json_response, human_time, AttrDict
from libs.wx.pay import WxPay
from apps.order.models import Order, OrderCourse
from threading import Thread
import json
import uuid
import logging
from datetime import datetime, timedelta

logger = logging.getLogger('error')

class OrderView(View):
    def get(self, request, order_id=None):
        # 获取单个订单详情
        if order_id:
            try:
                order = Order.objects.get(id=order_id)
                order_courses = OrderCourse.objects.filter(order=order)
                
                # 构建响应数据
                data = order.to_dict()
                data['courses'] = [course.to_dict() for course in order_courses]
                
                return json_response(data)
            except Order.DoesNotExist:
                return json_response(error='订单不存在')
            except Exception as e:
                logger.exception(f'获取订单详情失败: {str(e)}')
                return json_response(error=str(e))
        
        # 获取订单列表
        orders = Order.objects.all()
        
        # 应用过滤条件
        # 订单编号
        order_no = request.GET.get('order_no')
        if order_no:
            orders = orders.filter(order_no__icontains=order_no)
        
        # 学生姓名
        student_name = request.GET.get('student_name')
        if student_name:
            orders = orders.filter(student_name__icontains=student_name)
        
        # 家长姓名
        parent_name = request.GET.get('parent_name')
        if parent_name:
            orders = orders.filter(parent_name__icontains=parent_name)
        
        # 家长手机
        parent_phone = request.GET.get('parent_phone')
        if parent_phone:
            orders = orders.filter(parent_phone__icontains=parent_phone)
        
        # 学员类型
        student_type = request.GET.get('student_type')
        if student_type:
            orders = orders.filter(student_type=student_type)
        
        # 上课类型
        class_type = request.GET.get('class_type')
        if class_type:
            orders = orders.filter(class_type=class_type)
        
        # 年级
        grade = request.GET.get('grade')
        if grade:
            orders = orders.filter(grade=grade)
        
        # 订单状态
        status = request.GET.get('status')
        if status:
            orders = orders.filter(status=status)
        
        # 支付方式
        payment_type = request.GET.get('payment_type')
        if payment_type:
            orders = orders.filter(payment_type=payment_type)
        
        # 学校名称
        school_name = request.GET.get('school_name')
        if school_name:
            orders = orders.filter(school_name__icontains=school_name)
        
        # 创建时间范围
        start_date = request.GET.get('start_date')
        end_date = request.GET.get('end_date')
        if start_date and end_date:
            try:
                start_datetime = datetime.strptime(start_date, '%Y-%m-%d')
                end_datetime = datetime.strptime(end_date, '%Y-%m-%d') + timedelta(days=1)
                orders = orders.filter(created_at__gte=start_datetime, created_at__lt=end_datetime)
            except ValueError:
                pass
        
        # 按创建时间倒序排序
        orders = orders.order_by('-created_at')
        
        # 转换为字典列表
        result = [order.to_dict() for order in orders]
        
        return json_response(result)
    
    def post(self, request):
        form, error = JsonParser(
            Argument('student_id', help='请输入学员ID'),
            Argument('course_id', help='请输入课程ID'),
            Argument('price', help='请输入价格'),
            Argument('pay_type', help='请输入支付方式'),
        ).parse(request.body)
        if error is None:
            if form.id:
                Order.objects.filter(pk=form.id).update(**form)
            else:
                Order.objects.create(**form)
        return json_response(error=error)
    
    def delete(self, request, order_id):
        Order.objects.filter(pk=order_id).update(is_delete=True)
        return json_response()

class OrderCancelView(View):
    """取消订单"""
    def post(self, request, order_id):
        try:
            order = Order.objects.get(id=order_id)
            
            # 只有待支付的订单可以取消
            if order.status != 'pending':
                return json_response(error='只有待支付的订单可以取消')
            
            # 更新订单状态
            order.status = 'cancelled'
            order.save()
            
            return json_response({'success': True})
        except Order.DoesNotExist:
            return json_response(error='订单不存在')
        except Exception as e:
            logger.exception(f'取消订单失败: {str(e)}')
            return json_response(error=str(e))

class OrderConfirmPaymentView(View):
    """确认线下支付"""
    def post(self, request, order_id):
        try:
            order = Order.objects.get(id=order_id)
            
            # 只有待支付的线下支付订单可以确认
            if order.status != 'pending':
                return json_response(error='只有待支付的订单可以确认支付')
            
            if order.payment_type != 'offline':
                return json_response(error='只有线下支付的订单可以手动确认支付')
            
            # 更新订单状态
            order.status = 'paid'
            order.paid_time = timezone.now()
            order.save()
            
            return json_response({'success': True})
        except Order.DoesNotExist:
            return json_response(error='订单不存在')
        except Exception as e:
            logger.exception(f'确认支付失败: {str(e)}')
            return json_response(error=str(e))
